package controllers;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import models.Food;
import models.OrderItem;
import models.User;
import models.dao.FoodDAO;
import models.dao.OrderDAO;
import play.mvc.Controller;
import play.mvc.Http;

import com.google.gson.Gson;

public class Application extends Controller {

	public static void index() {
		String w_username = "";
		render(w_username);
	}

	public static void list() {
		User user = getCurrentUser();
		List<Food> objects = FoodDAO.getTodayFoodList();
		String w_username = "";
		render(user, objects,w_username);
	}

	public static void placeOrder(String user_name, int food_id) {
		String result = "";
		OrderItem order = null;
		try {
			order = OrderDAO.placeOrder(user_name, getCurrentUserIp(), food_id);
		} catch (Exception ex) {
			result = String.format("{\"result\":\"%s\",\"message\":\"%s\",\"order\":%s}}", "error",
					ex.getMessage(), "null");
		}
		result = String.format("{\"result\":\"%s\",\"message\":\"%s\",\"order\":%s}", "succ","Order placed!",
				new Gson().toJson(order));
		Http.Cookie cookie = new Http.Cookie();
		cookie.name = utils.Constants.COOKIE_USER_NAME;
		cookie.value = user_name;
		response.cookies.put(utils.Constants.COOKIE_USER_NAME, cookie);
		
		renderJSON(result);
	}

	public static void ordersInfo() {
		List<OrderItem> orders = OrderDAO.getTodayOrders();
		Map<String,List<OrderItem>> foodGroups = new HashMap<String,List<OrderItem>>();
		for(OrderItem item : orders)
		{
			if(!foodGroups.containsKey(item.food.name))
			{
				foodGroups.put(item.food.name, new ArrayList<OrderItem>());
			}
			foodGroups.get(item.food.name).add(item);
		}
		render(orders,foodGroups);
	}

	private static User getCurrentUser() {
		if (request.cookies.containsKey(utils.Constants.COOKIE_USER_NAME)) {
			User user = new User();
			user.ip = request.remoteAddress;
			user.userName = request.cookies
					.get(utils.Constants.COOKIE_USER_NAME).value;
			return user;
		} else {
			return null;
		}
	}
	
	private static String getWindowsUsername(){
	String auth = request.headers.get("Authorization").value();
	if (auth == null) {
        //response.setStatus(response.SC_UNAUTHORIZED);
        //response.setHeader("WWW-Authenticate", "NTLM");
        return "";
	}
	if (auth.startsWith("NTLM ")) { 
			byte[] msg = new byte[0];
			try
			{
			
msg			= 
			   new sun.misc.BASE64Decoder().decodeBuffer(auth.substring(5));
			   }
			   catch(Exception ex){};
			int off = 0, length, offset;
			String s;

			if (msg[8] == 1) { 
				off = 18;

				byte z = 0;
				byte[] msg1 =
					{(byte)'N', (byte)'T', (byte)'L', (byte)'M', (byte)'S',
					(byte)'S', (byte)'P', z,
					(byte)2, z, z, z, z, z, z, z,
					(byte)40, z, z, z, (byte)1, (byte)130, z, z,
					z, (byte)2, (byte)2, (byte)2, z, z, z, z, // 
					z, z, z, z, z, z, z, z};
				// 
				//response.setStatus(response.SC_UNAUTHORIZED);
				//response.setHeader("WWW-Authenticate", "NTLM " 
				//   + new sun.misc.BASE64Encoder().encodeBuffer(msg1).trim());
				return "";
			} 
			else if (msg[8] == 3) { 
					off = 30;
					length = msg[off+17]*256 + msg[off+16];
					offset = msg[off+19]*256 + msg[off+18];
					s = new String(msg, offset, length);
					//out.println(s + " ");
			} 
			else
				return "";

			length = msg[off+1]*256 + msg[off];
			offset = msg[off+3]*256 + msg[off+2];
			s = new String(msg, offset, length);
			//out.println(s + " ");
			length = msg[off+9]*256 + msg[off+8];
			offset = msg[off+11]*256 + msg[off+10];
			s = new String(msg, offset, length);
			return s;
		}
		
		return "";
	}

	private static String getCurrentUserIp() {
		return request.remoteAddress;
	}

}